package beego

import (
	"encoding/json"
	"gitee.com/apply/go-skyteam/pkg/web/beego/utils"
	"github.com/beego/beego/v2/server/web"
	"net/url"
)

type BaseController struct {
	web.Controller
}

func (c BaseController) Response(data interface{}, err error) {
	var response utils.JsonResponse
	if err != nil {
		response = utils.ResponseError(c.Ctx, err)
	} else {
		response = utils.ResponseData(c.Ctx, data)
	}
	c.Data["json"] = response
	_ = c.ServeJSON()
}

func (c BaseController) Unmarshal(v interface{}) error {
	body := c.Ctx.Input.RequestBody
	if len(body) == 0 {
		body = []byte("{}")
	}
	return json.Unmarshal(body, v)
}

func (c BaseController) BindQuery(v interface{}) {
	rawQuery := c.Ctx.Request.URL.RawQuery
	values, _ := url.ParseQuery(rawQuery)
	data := make(map[string]interface{})
	for key,_:=range values {
		data[key] = values.Get(key)
	}
	mBytes,_:=json.Marshal(data)
	_ = json.Unmarshal(mBytes, &v)
}

// 获取接口语言包
func (c BaseController) AcceptLang() string {
	lang := c.Ctx.Request.Header.Get("accept-lang")
	if lang == "" {
		lang = "zh"
	}
	return lang
}
